import axios from "axios";
import Config from "@/config/index";
const baseURL = Config.baseUrl;
const tokenName = Config.request.tokenName;
const $loading = Config.Loading;

class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl;
    this.queue = {};
    this.Loading = null;
  }
  /* axios默认配置 */
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      /* headers: {
        "content-type": "application/json"
      }, */
      method: "get"
    };
    return config;
  }
  /**
   * 当请求数为0时，关闭loading动画
   *
   * @param {String} url
   * @memberof HttpRequest
   */
  distroy(url) {
    // debugger;
    delete this.queue[url];
    if (!Object.keys(this.queue).length) {
      // 关闭loading动画
      setTimeout(() => {
        this.Loading.close();
      }, 500);
    }
  }
  /* 当请求数大于0时，开启loading动画 */
  loading() {
    if (Object.keys(this.queue).length > 0) {
      // 执行loading函数
      this.Loading = $loading({
        text: "加载中",
        // fullscreen: false,
        background: "transparent"
      });
    }
  }
  /**
   * 拦截器
   *
   * @param {Object} instance
   * @param {String} url
   * @param {Boolean} loading
   * @param {Boolean} get_token
   * @memberof HttpRequest
   */
  interceptors(instance, url, loading, get_token) {
    let token = window.localStorage.getItem(tokenName);
    // 请求拦截
    instance.interceptors.request.use(
      config => {
        if (loading) {
          // 把当前url放入queue队列中
          this.queue[url] = true;
          // 添加一个全局的loading,如果队列不为0，则执行loading函数
          this.loading();
        }
        // 在headers上添加token
        if (get_token && token) {
          config.headers[this.token] = token;
        }
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );
    // 响应拦截
    instance.interceptors.response.use(
      result => {
        if (loading) {
          this.distroy(url);
        }
        return result.data;
      },
      error => {
        if (loading) {
          this.distroy(url);
        }
        return Promise.reject(error);
      }
    );
  }
  /**
   * 创建axios实例
   *
   * @param {Object} options
   * @returns
   * @memberof HttpRequest
   */
  axios(options) {
    const instance = axios.create();
    options = Object.assign(this.getInsideConfig(), options);
    let { url, loading = false, get_token = false } = options;
    this.interceptors(instance, url, loading, get_token);
    return instance(options);
  }
}

export default HttpRequest;
